package app.Insam.VNC;

import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;

public class InsamScheduler{
	public static final String TAG = "InsamScheduler";
	public static final int SCHEDULER_IDLE = 0x10;
	
	protected Handler mServiceHandler;
	protected static Thread mWorker;
	protected boolean run=true;
	protected static int mtaskId = SCHEDULER_IDLE;
	protected static long mWhen=0;	
	protected int mLeft=0;

	public InsamScheduler(Handler _handler) {
		Log.v(TAG, "start Scheduler");
		mServiceHandler = _handler;	
		
		mWorker = new Thread() {
			@Override
			public void run() {
				while(run) {	
					mLeft = (int)(mWhen - SystemClock.elapsedRealtime());
	//				if(mtaskId!=SCHEDULER_IDLE && (mWhen < SystemClock.elapsedRealtime())) {
					if(mtaskId!=SCHEDULER_IDLE && (mLeft < 0)) {
						Log.v(TAG, "send msg, id:" + mtaskId);
						mServiceHandler.sendEmptyMessage(mtaskId);
						mtaskId=SCHEDULER_IDLE;
					} 
					
					try {
						if(mLeft>InsamApp.TIME_RESCAN_MINIMUM>>>1 || mLeft < 0 ) {
							mLeft=InsamApp.TIME_RESCAN_MINIMUM>>>1;
						}						
						InsamDebugger.updateNextUptime(mLeft);
						
						Log.v(TAG, "sleep " + mLeft + "ms");
						sleep(mLeft);
					} catch (InterruptedException e) { 
						Log.d(TAG, String.format("sleep interrupted"));
					}
				}	
			}
		};
		mWorker.start();
	}
	
	public synchronized void schedule(int _taskId, long _delay) {		
		long now = SystemClock.elapsedRealtime();
		if(mtaskId!=SCHEDULER_IDLE) {
			Log.d(TAG, "cancel task/id:"+ mtaskId);
		}
		mWhen = now + _delay;
		mtaskId = _taskId;
		Log.i(TAG, String.format("schedule new task, id:%d after %dms", mtaskId, _delay));
	}
	
	public void execute(int _taskId) {
		mServiceHandler.sendEmptyMessage(_taskId);
	}
	
	public boolean isIdle() {
		return mtaskId==SCHEDULER_IDLE;
	}
	
	public void stop() {
		Log.d(TAG, "stop Scheduler");
		run=false;
	}
	
	public static void compel(int _taskId) {
		mtaskId = _taskId;
		mWhen=0;
		mWorker.interrupt();
	}
	
/*	
	public boolean check() {
		Log.d(TAG, String.format("check scheduling"));
		if(mtaskId!=SCHEDULER_IDLE && (mWhen < SystemClock.elapsedRealtime())) {
			mWorker.interrupt();
			return true;
		}
		return false;
	}
*/
}
